import {Tray, app, Menu, ipcMain} from "electron";
import path from 'path'

require('console-color-mr');


class TrayController {
  constructor (mainController) {
    this.mainController = mainController
    this.tray = null
    this.platform = require('os').platform()
    this.init()
  }

  init () {
    this.tray = new Tray(this.getPath('../icons/tray-icons/online.png'))
    this.tray.setToolTip(app.getName())
    const context = Menu.buildFromTemplate([
      {
        label: '打开主界面',
        click: () => this.mainController.toggle()
      },
      {
        label: '设置',
        click: () => this.mainController.toggle()
      },
      {
        label: '退出',
        click: () => this.exitApp()
      }
    ])
    this.tray.setContextMenu(context)
    this.tray.on('click', () => this.mainController.toggle())
    ipcMain.on('networkStatus.offline', (event, value) => {
      console.warn('网络异常:离线')
      this.tray.setImage(this.getPath('../icons/tray-icons/offline.png'))
    })
    ipcMain.on('networkStatus.online', (event, value) => {
      console.info('网络已连接')
      this.tray.setImage(this.getPath('../icons/tray-icons/online.png'))
    })
  }

  exitApp () {
    app.exit(0);
  }

  getPath (file) {
    return path.join(__dirname, file)
  }
}

export default TrayController
